package com.books4sale.admin.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;

import com.books4sale.admin.dto.Book;
import com.books4sale.admin.dto.tools.Helper;

public class AllBooksServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		List<Book> results = Helper.get().getAllBooks();
		PrintWriter writer = resp.getWriter();

		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json");

		JSONWriter jsonWriter = new JSONWriter(writer);
		try {
			jsonWriter.object().key("pageNumber").value("1").key("books")
					.array();

			for (Book book : results) {

				jsonWriter.object().key("bookId").value(book.getId()).key(
						"bookName").value(book.getBookName())
						.key("bookSubject").value(book.getBookSubject()).key(
								"bookCollage").value(book.getBookCollage())
						.key("bookPrice").value(book.getBookPrice())
						.endObject();

			}
			jsonWriter.endArray().endObject();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// try {
		// //
		// //
		// jsonWriter.object().key("page").value("1").endObject();//.key("books").value(o)array();
		// jsonWriter.object().key("pageNumber").value("1").key("result").array();
		// } catch (JSONException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// }
		// for (int i = 0; i < 10; i++) {
		// try {
		// jsonWriter.object().key("bookName_"+i).value("value")
		// .key("bookSubject").value("value").endObject();
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		//				
		// try {
		// jsonWriter.endArray().endObject();
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
	}
}
